package com.example.android2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.example.android2.R;


public class MainActivity extends AppCompatActivity {

    private SMSReceiver smsReceiver;
    private class SMSReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("接收到短信通知");
            String phone = "";
            StringBuilder stringBuilder = new StringBuilder();
            Bundle bundle = intent.getExtras();
            String format = intent.getStringExtra("format");
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                for (Object o : pdus) {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) o, format);
                    phone = smsMessage.getOriginatingAddress();
                    stringBuilder.append(smsMessage.getMessageBody());
                }
            }
            System.out.println("接收到的短信:" + phone + "|" + stringBuilder.toString());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        smsReceiver = new SMSReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(smsReceiver);
    }

}
